package com.atguigu.gulimall.prodect.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.prodect.dao.CategoryDao;
import com.atguigu.gulimall.prodect.entity.CategoryEntity;
import com.atguigu.gulimall.prodect.service.CategoryService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 商品分类
     * @return
     */
    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> list = this.list();
        //过滤出分组等于一的
        Map<Integer, List<CategoryEntity>> map = list.stream().collect(Collectors.groupingBy(categoryEntity -> categoryEntity.getCatLevel()));
        List<CategoryEntity> rootCategories  = map.get(1).stream().sorted(Comparator.comparingInt(CategoryEntity::getSort)).collect(Collectors.toList());
        if (rootCategories!=null){
            rootCategories.stream().forEach(categoryEntity -> buildTree(categoryEntity,map));
        }
        return rootCategories;
    }

    /**
     * 删除分类菜单
     * @param catIds
     */
    @Override
    public void removeMenuByIds(Long[] catIds) {
        //TODO 删除逻辑，有其他地方用到改分类则不能删除
        this.removeByIds(Arrays.asList(catIds));
    }











    private void buildTree(CategoryEntity categoryEntity, Map<Integer, List<CategoryEntity>> map) {
        List<CategoryEntity> list = map.get(categoryEntity.getCatLevel() + 1);

        // 如果 list 为 null，则终止递归
        if (list == null) {
            return;
        }

        // 过滤和收集子节点
        List<CategoryEntity> collect = list.stream()
                .filter(child -> child.getParentCid() != null && child.getParentCid().equals(categoryEntity.getCatId()))
                .filter(child -> child.getSort() != null)
                .sorted(Comparator.comparingInt(CategoryEntity::getSort))
                .collect(Collectors.toList());

        // 设置当前节点的子节点
        categoryEntity.setChildren(collect);

        // 递归处理每个子节点
        collect.forEach(child -> buildTree(child, map));
    }


}